import {Plugin, TransformResult} from "vite"
import {TransformOptions} from "@babel/core";
import babel from "@babel/core";
import {esbuildPluginBabel} from "./esbuildBabel";
import {Loader} from "esbuild";

export interface VitePluginBabelConfig {
  babelConfig?: TransformOptions;
  filterFile?: RegExp;
  loader?: Loader | ((path: string) => Loader);
}

let DEFAULT_FILTER_FILE = /\.(js|jsx|ts|tsx)$/

export default function vitePluginBabel(config?: VitePluginBabelConfig): Plugin {
  if (!config) {
    config = {}
  }
  return {
    name: 'vite:vite-plugin-babel',
    enforce: 'pre', // 也是使用预编译
    config() {
      return {
        optimizeDeps: {
          esbuildOptions: {
            plugins: [
              esbuildPluginBabel({
                config: {...config.babelConfig},
                filter: config.filterFile || DEFAULT_FILTER_FILE,
                loader: config.loader,
              }),
            ],
          },
        },
      };
    },
    transform(code: string, id: string): Promise<TransformResult> | TransformResult {
      if (id.includes('node_modules')) {
        return
      }
      if (!config.filterFile) {
        config.filterFile = DEFAULT_FILTER_FILE
      }
      // 判断？不在处理虚拟文件
      if (!id.includes('?') && config.filterFile.test(id)) {
        const babelFileResult = babel.transformSync(code, {
          filename: id,
          ...config.babelConfig
        });
        return {
          code: babelFileResult.code,
          map: babelFileResult.map
        }
      }
    }
  }
}
